<?php

namespace App\Lib;

class Crypt3DesEcb
{
    /**
     * @var string
     */
    protected $key = '';

    /**
     * @param $key
     */
    function __construct($key)
    {
        $this->key = $key;
    }

    function encrypt($value)
    {
        $iv = substr($this->key, 0, 8);
        $ret = openssl_encrypt($value, 'DES-EDE3-CBC', $this->key, 0, $iv);
        if (false === $ret) {
            return openssl_error_string();
        }

        return $ret;
    }

    function decrypt($value)
    {
        $iv = substr($this->key, 0, 8);
        $ret = openssl_decrypt($value, 'DES-EDE3-CBC', $this->key, 0, $iv);
        if (false === $ret) {
            return openssl_error_string();
        }
        return $ret;
    }

    /**
     * 加密数据
     *
     * @param $data
     * @return string
     */
    function encryptBak($data)
    {
        // $cipher = 'DES-EDE3';
        $cipher = 'DES-EDE3-CBC';
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = openssl_random_pseudo_bytes($ivlen);
        $data = $this->pkcs5_pad($data);
        $key = str_pad($this->key, 24, '0');
        $key = substr($key, 0, 24);
        //openssl加密3des解析多出字符问题 options 设置为 OPENSSL_RAW_DATA | OPENSSL_NO_PADDING 即可解决
        $encryptData = openssl_encrypt($data, $cipher, $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
        return $encryptData;

    }

    /**
     * 解密数据
     *
     * @param $data
     * @return bool|string
     */
    function decryptBak($data)
    {
        // $cipher = 'DES-EDE3';
        $cipher = 'DES-EDE3-CBC';
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = openssl_random_pseudo_bytes($ivlen);
        $key = str_pad($this->key, 24, '0');
        $key = substr($key, 0, 24);
        $decryData = openssl_decrypt($data, $cipher, $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $iv);
        if (empty($decryData)) {
            return '';
        }
        $decryData = $this->pkcs5_unpad($decryData);
        return $decryData;
    }

    /**
     * 填充加密后数据
     *
     * @param $text
     * @param $blocksize
     * @return string
     */
    function pkcs5_pad($text, $blocksize = 8)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    /**
     * 去除填充字符
     *
     * @param $text
     * @return bool|string
     */
    function pkcs5_unpad($text)
    {
        $pad = ord($text{strlen($text) - 1});
        if ($pad > strlen($text)) {
            return FALSE;
        }
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
            return FALSE;
        }
        return substr($text, 0, -1 * $pad);
    }
}